<?php


namespace common\service;

use common\model\ProjectMemberModel;
use support\SingletonTrait;
use Webman\Stomp\Client;

class TenantUserService
{

    // 单例工具
    use SingletonTrait;


    /**
     * 部门用户二级树
     * @return mixed
     */
    public function tree($param)
    {
        $res = teamones_request('teamones-im', 'tenant_user/tree', ['param' => $param])['data'];
        if (empty($res)) {
            return $res;
        }
        $userIdArray = [];
        foreach ($res as $department) {
            foreach ($department['children'] as $user) {
                $userIdArray[$user['user']['id']] = $user['user']['id'];
            }
        }
        $users = UserService::getInstance()->getUsersByUnionIds($userIdArray, 'id,union_id,name,user_cert_id', false);
        $usersMap = array_column($users, null, 'union_id');
        $usersIdMap = array_column($users, 'union_id', 'id');

        $includeProjectInfo = ($param['include_project_info'] ?? '') === 'yes';
        $projectIdList = split_array($param['project_id_list'] ?? []);
        $checkProjectInfo = $includeProjectInfo || !empty($projectIdList);

        if ($checkProjectInfo) {
            // 查出符合条件的项目成员
            // Hint 数据库group_concat_max_len配置，默认1024截断
            $where = empty($projectIdList) ? [] : ['project_id' => ['IN', $projectIdList]];
            $projectMemberList = model(ProjectMemberModel::class)
                ->where($where)
                ->order('user_id,project_id')
                ->field(
                    'user_id'
                    . ', group_concat(distinct project_id) as project_id_list'
                    . ', is_delete'
                )
                ->group('user_id, is_delete')
                ->select();
            foreach ($projectMemberList as $pmInfo) {
                $pmUserUnionId = $usersIdMap[$pmInfo['user_id']] ?? "No such user";
                if (!isset($usersMap[$pmUserUnionId])) {
                    continue;
                }
                $inProjectState = $pmInfo['is_delete'] == 0 ? 'current' : 'former';
                if ($includeProjectInfo) {
                    $usersMap[$pmUserUnionId]['project_' . $inProjectState] = $pmInfo['project_id_list'];
                }
                if (!empty($projectIdList)) {
                    if (($usersMap[$pmUserUnionId]['project_state'] ?? "former") == "current") {
                        continue;
                    }
                    $usersMap[$pmUserUnionId]['project_state'] = $inProjectState;
                }
            }
        }

        // 如果saas_user为空 发送异步队列处理同步用户
        $needSyncUserIdList = [];
        foreach ($res as &$department) {
            foreach ($department['children'] as &$user) {
                $user['saas_user'] = $usersMap[$user['user']['id']] ?? null;
                if (empty($user['saas_user'])) {
                    $needSyncUserIdList[$user['user']['id']] = $user['user']['id'];
                }
            }
        }
        if (!empty($needSyncUserIdList)) {
            Client::send('sync_user', build_queue_data_with_xu(['user_id_list' => array_values($needSyncUserIdList)]));
        }
        if ($checkProjectInfo) {
            $departmentTree = [];
            foreach ($res as $departmentInfo) {
                $children = [];
                foreach ($departmentInfo['children'] as $user) {
                    if (isset($usersMap[$user['user']['id']]['project_state'])) {
                        $children[] = $user;
                    }
                }
                if (!empty($children)) {
                    // 根据项目查用户，则没有用户的部门不返回
                    $departmentInfo['children'] = $children;
                    $departmentTree[] = $departmentInfo;
                }
            }
            $res = $departmentTree;
        }
        return $res;
    }
}
